package org.buptsse.ui;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.buptsse.ui.R;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;

public class MainStudyActivity extends ListActivity {
    /** Called when the activity is first created. */
	String replyContent,replyTitle,myName;
	private Handler dialogHandler = null;
	private static final int PROGRESSDIALOG = 1;
	private static final int DIALOG = 2;
	private static final int PROGRESS = 3;
	private final int finish = 0;
	private final int end = 1;
	int page=0,cid=1;
	SimpleAdapter listAdapter;
    ArrayList<HashMap<String, String>> discusslist =new ArrayList<HashMap<String,String>>();
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.coursediscuss);
        dialogHandler = new Handler() {
			public void handleMessage(Message msg) {
				super.handleMessage(msg);
				switch (msg.what) {
				case finish:
					listAdapter =new SimpleAdapter(MainStudyActivity.this, discusslist, R.layout.coursepost, new String[]{"smalltitle" , "smallusername","time","replynum"}, new int[]{R.id.title , R.id.username,R.id.time,R.id.replynum}); 
			        setListAdapter(listAdapter); 
					dismissDialog(PROGRESSDIALOG);
					break;
				case end:
					listAdapter =new SimpleAdapter(MainStudyActivity.this, discusslist, R.layout.coursepost, new String[]{"smalltitle" , "smallusername","time","replynum"}, new int[]{R.id.title , R.id.username,R.id.time,R.id.replynum}); 
			        setListAdapter(listAdapter);
			        dismissDialog(PROGRESS);
				}
			}
		};  
    }
    
    protected Dialog onCreateDialog(int id) {  
        // TODO Auto-generated method stub  
        if(id==1){  
        	return this.buildProgressDialog(MainStudyActivity.this);
        }  
        else if(id==2)
        {
        	return this.buildDialog(MainStudyActivity.this);
        }
        else if(id==3)
        {
        	return this.buildProgress(MainStudyActivity.this);
        	
        }
        else
        {
        	return null;
        }
    }
    
    private Dialog buildProgress(Context context)
    {
    	Dialog resultDialog = new ProgressDialog(this);;
    	resultDialog.setTitle("正在发帖……");
    	((ProgressDialog) resultDialog).setProgressStyle(ProgressDialog.STYLE_SPINNER);
    	return resultDialog;
    }
    
    private Dialog buildProgressDialog(Context context)
    {
    	Dialog resultDialog = new ProgressDialog(this);;
    	resultDialog.setTitle("加载中……");
    	((ProgressDialog) resultDialog).setProgressStyle(ProgressDialog.STYLE_SPINNER);
    	return resultDialog;

    }
    
    private void postReply()
    {
    	CloudLearningApp cloudApp=(CloudLearningApp)getApplication();
    	myName=cloudApp.getUsername();
    	HttpClient client=new DefaultHttpClient();
    	StringBuilder builder=new StringBuilder();
    	JSONArray jsonarray=null;
    	HttpPost post=new HttpPost("http://rebook.sinaapp.com/mainpost.php");
    	List<NameValuePair> parameter=new ArrayList<NameValuePair>();
    	parameter.add(new BasicNameValuePair("cid",String.valueOf(cid)));
    	parameter.add(new BasicNameValuePair("username",myName));
    	parameter.add(new BasicNameValuePair("content",replyContent));
    	parameter.add(new BasicNameValuePair("title",replyTitle));
    	try {
			post.setEntity(new UrlEncodedFormEntity(parameter,HTTP.UTF_8));
			HttpResponse response=client.execute(post);
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    }
    
    class GetData extends Thread
    {
 	   public void run()
 	   {
 		   postReply();
 		   GetJsonArray();
 		   if(dialogHandler!=null)dialogHandler.sendEmptyMessage(end);
 	   }
    }
    
    protected void Afterpost() {
	    dismissDialog(DIALOG);
    	showDialog(PROGRESS);
    }
    
    private Dialog buildDialog(Context context){  
    	LayoutInflater inflater = (LayoutInflater) MainStudyActivity.this.getSystemService(LAYOUT_INFLATER_SERVICE);
        final View view = inflater.inflate(R.layout.mainreply, null);
        
        AlertDialog.Builder builder =   new AlertDialog.Builder(context);
        builder.setTitle("发帖").setView(view);
        builder.setMessage("请输入帖子标题和内容");  
        builder.setPositiveButton("发帖",new DialogInterface.OnClickListener() {  
              
            @Override 
            public void onClick(DialogInterface dialog, int which) {  
                // TODO Auto-generated method stub  
            	EditText titleText=(EditText)view.findViewById(R.id.titletext);
            	EditText replyText=(EditText)view.findViewById(R.id.edittext);
            	replyContent=replyText.getText().toString(); 
            	replyTitle=titleText.getText().toString();
                if(replyContent.equals("")||replyTitle.equals(""))
                {
                	Toast.makeText(MainStudyActivity.this, "帖子标题和内容不能为空", Toast.LENGTH_SHORT).show();
                }
                 else
                {
                 	replyText.setText(null);
                	Afterpost();
                }
            }  
        });  

        builder.setNegativeButton("取消",new DialogInterface.OnClickListener() {  
            
            @Override 
            public void onClick(DialogInterface dialog, int which) {  
            	EditText replyText=(EditText)view.findViewById(R.id.edittext);
                // TODO Auto-generated method stub  
            	replyText.setText(null);
            	dialog.dismiss();
            }  
        });
        return builder.create();  
    }  
    
    protected void onPrepareDialog(int id, Dialog dialog) {  
        // TODO Auto-generated method stub  
        super.onPrepareDialog(id, dialog);  
        if(id==1)
        {
        	new GetList().start();
        }
        else if(id==3)
        {
        	new GetData().start();
        }
    }  

	@Override
	protected void onStart() {
		// TODO Auto-generated method stub
		super.onStart();
		showDialog(PROGRESSDIALOG);
	}

	class GetList extends Thread
	{
		public void run()
		{
			System.out.println("进入GetList线程");
			GetJsonArray();
			dialogHandler.sendEmptyMessage(finish);
		}
	}
	
	private JSONArray GetJsonArray()
    {
    	HttpClient client=new DefaultHttpClient();
    	StringBuilder builder=new StringBuilder();
    	JSONArray jsonarray=null;
    	HttpPost post=new HttpPost("http://rebook.sinaapp.com/discuss.php");
    	List<NameValuePair> parameter=new ArrayList<NameValuePair>(); 
    	parameter.add(new BasicNameValuePair("page",String.valueOf(page)));
    	parameter.add(new BasicNameValuePair("cid",String.valueOf(cid)));
    	try {
    		post.setEntity(new UrlEncodedFormEntity(parameter,HTTP.UTF_8));
			HttpResponse response=client.execute(post);
			BufferedReader reader=new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
			for(String s=reader.readLine();s!=null;s=reader.readLine())
			{
				builder.append(s);
			}
			if(builder.toString().equals("end"))
			{
				System.out.println("th end");
				page=page-1;
			}
			else
			{
				jsonarray=new JSONArray(builder.toString());
				JSONObject jsonObject;
				discusslist.clear();
				for(int i=0;i<jsonarray.length();i++)
				{
					jsonObject=jsonarray.getJSONObject(i);
					HashMap<String,String> map=new HashMap<String,String>();
					if(jsonObject.getString("title").length()>10)
					{
						StringBuffer smalltitle=new StringBuffer(jsonObject.getString("title").substring(0,9));
						smalltitle.append("……");
						map.put("smalltitle",smalltitle.toString());
					}
					else
					{
						map.put("smalltitle",jsonObject.getString("title"));
					}
					
					if(jsonObject.getString("username").length()>7)
					{
						StringBuffer smallname=new StringBuffer(jsonObject.getString("username").substring(0,7));
						smallname.append("……");
						map.put("smallusername",smallname.toString());
					}
					else
					{
						map.put("smallusername",jsonObject.getString("username"));
					}
					map.put("title",jsonObject.getString("title"));
					map.put("username",jsonObject.getString("username"));
					map.put("time",jsonObject.getString("time"));
					map.put("replynum",jsonObject.getString("replynum"));
					map.put("postid",jsonObject.getString("postid"));
					map.put("content",jsonObject.getString("content"));
					discusslist.add(map);
				}
			}
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			System.out.println("client---->"+e.toString());
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			System.out.println("IO---->"+e.toString());
			e.printStackTrace();
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			System.out.println("json---->"+e.toString());
			e.printStackTrace();
		}
		return jsonarray;
    }

	protected void onListItemClick(ListView l, View v, int position, long id) {
		super.onListItemClick(l, v, position, id);
		HashMap map = discusslist.get(position);
		String username = (String) map.get("username");
		String postid=(String)map.get("postid");
		String time=(String)map.get("time");
		String replynum=(String)map.get("replynum");
		String title=(String)map.get("title");
		String content=(String)map.get("content");
		Intent intent=new Intent();
		intent.putExtra("postid",postid);
		intent.putExtra("username",username);
		intent.putExtra("time",time);
		intent.putExtra("replynum",replynum);
		intent.putExtra("title",title);
		intent.putExtra("content",content);
		intent.setClass(MainStudyActivity.this,PostReplyActivity.class);
		MainStudyActivity.this.startActivity(intent);
	}
	
	public boolean onCreateOptionsMenu(Menu menu) {
	        // TODO Auto-generated method stub
	        menu.add(0, 1, 1, "上一页");
	        menu.add(0, 2, 2, "下一页");
	        menu.add(0, 3, 3, "发帖");
	        return super.onCreateOptionsMenu(menu);
	    }
	
    public boolean onOptionsItemSelected(MenuItem item) {
        // TODO Auto-generated method stub
        if(item.getItemId() == 1){
        	System.out.println("点击了上一页");
        	if(page!=0)
        	{
        		page=page-1;
        		showDialog(PROGRESSDIALOG);
        	}
        }
        else if(item.getItemId() == 2){
        	System.out.println("点击了下一页");
        	page=page+1;
        	showDialog(PROGRESSDIALOG);
        } 
        else if(item.getItemId()==3)
        {
        	showDialog(DIALOG);
        }
        return true;
    }
	
}